package com.tc.dispatch.web.schedule.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import com.tc.dispatch.gsalgorithm.spec.parse;
import com.tc.dispatch.gsservice.basic.common.regulation;
import com.tc.dispatch.gsservice.ejb.GSServiceLocal;
import com.tc.dispatch.gsservice.exception.GSException;
import com.tc.dispatch.gsservice.model.OrderSumMain;
import com.tc.dispatch.gsservice.model.OrderSumSub;
import com.tc.dispatch.gsservice.model.ProcessStep;
import com.tc.dispatch.gsservice.model.QianDaoYield;
import com.tc.dispatch.web.gsservice.gsHelper;
import com.tc.dispatch.web.model.combinedOrder;
import com.tc.dispatch.web.util.DateJsonValueProcessor;

public class orderJiaGongIndex extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public orderJiaGongIndex() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}



	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html; charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");
		if (action == null)
			action = "";

		GSServiceLocal gss = gsHelper.getGSServiceLocal();
		HttpSession sess = request.getSession();
		OrderSumMain osm = new OrderSumMain();
		OrderSumMain osmDef = new OrderSumMain();
		String pos = "0";
		if (sess.getAttribute("position") != null) {
			pos = (String) sess.getAttribute("position");
		}
		;
		if (action.equals("default")) {
			try {
			if (Integer.parseInt(pos) == 2)// 表示 刚开始
			{

			

					osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
					osmDef = (OrderSumMain) sess
							.getAttribute("OrderSumMainDef");
					
					sess.setAttribute("position", "3");

				
			} else {
				osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
				osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");
			}
			} catch (Exception e) {
				System.out.println("update error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}

			JSONObject json = new JSONObject();
			JsonConfig cfg = new JsonConfig();
			cfg.registerJsonValueProcessor(java.util.Date.class,
					new DateJsonValueProcessor());
			cfg.registerJsonValueProcessor(java.sql.Date.class,
					new DateJsonValueProcessor());

			// BeanUtils.copyProperties();
			json.put("totalProperty", new Integer(1));
			List ret = new ArrayList();
			combinedOrder corder = new combinedOrder();
			//corder.setOsm(osm.convertToString());
			//corder.setOsm2(osmDef.convertToString());
			ret.add(corder);

			JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
			json.put("root", arr);

			response.getWriter().print(json);
		} else if (action.equals("update")) {

			osm = (OrderSumMain) sess.getAttribute("OrderSumMain");
			osmDef = (OrderSumMain) sess.getAttribute("OrderSumMainDef");

			String specType = request.getParameter("specType");
			String specType2 = request.getParameter("specType2");
			String scheme = request.getParameter("processScheme");
			String scheme2 = request.getParameter("processScheme2");
			try {
				osm.setSpecType(specType);
				osmDef.setSpecType(specType2);

				osm.setProcessScheme(Integer.valueOf(scheme));
				osmDef.setProcessScheme(Integer.valueOf(scheme));

				

				sess.removeAttribute("OrderSumMain");
				sess.setAttribute("OrderSumMain", osm);

				sess.removeAttribute("OrderSumMainDef");
				sess.setAttribute("OrderSumMainDef", osmDef);
				
				gss.updateOrderSumMain(osm);
				gss.updateOrderSumMain(osmDef);
				/* 下面需要建立子表的加工列表，根据加工计算加工面积，加工费啥的还没有算 */
				List processList = new ArrayList();

				List sortList = gss.findProcessStep(" where specName='"
						+ specType + "' and scheme=" + scheme+" order by processPos");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					OrderSumSub oss = new OrderSumSub();
					oss.setProcessName(ps.getProcessName());
					oss.setProcessPos(new Integer(ps.getProcessPos()));
					oss.setType((byte) 1);
					oss.setOrderSumId(osm.getId());
					oss.setProcessNum(new Integer(1));
					oss.setProcessYield(new Float(1));
					oss.setProcessUpdate(new Float(1));
					oss.setProcessArea(new Float(0));
					oss.setAfterSpec(osm.getSpec());
					processList.add(oss);
				}

				List processListDef = new ArrayList();

				it = sortList.iterator();
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					OrderSumSub oss = new OrderSumSub();
					oss.setProcessName(ps.getProcessName());
					oss.setProcessPos(new Integer(ps.getProcessPos()));
					oss.setProcessNum(new Integer(1));
					oss.setProcessYield(new Float(1));
					oss.setProcessUpdate(new Float(1));
					oss.setProcessArea(new Float(0));
					oss.setAfterSpec(osmDef.getSpec());
					oss.setType((byte) 0);
					oss.setOrderSumId(osmDef.getId());
					processListDef.add(oss);
				}

				sess.setAttribute("processList", processList);
				sess.setAttribute("processListDef", processListDef);

				// response.sendRedirect("order/orderProcessIndex.jsp");
			} catch (Exception e) {
				System.out.println("update error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}
			out.print("{success:true, data:'sucess'}");

		} else if (action.equals("sort")) {
			try {
				List sortList = gss.findProcessStep("");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();

				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(ps.getSpecName()) < 0) {
						ret.add(ps.getSpecName());
						retList.add(ps);
					} else {
						// sortList.remove(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				System.out.println("update error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}

		} else if (action.equals("scheme")) {
			try {
				String sort = request.getParameter("sortType");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "'");
				Iterator it = sortList.iterator();
				ProcessStep ps;
				List ret = new ArrayList();
				List retList = new ArrayList();
				while (it.hasNext()) {
					ps = (ProcessStep) it.next();
					if (ret.indexOf(new Integer(ps.getScheme())) < 0) {
						ret.add(new Integer(ps.getScheme()));
						retList.add(ps);
					}
				}
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				// json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(retList.toArray(), cfg);
				json.put("root", arr);
				// json.

				response.getWriter().print(json);
			} catch (GSException e) {
				System.out.println("update error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}
		} else if (action.equals("step")) {
			try {
				String sort = request.getParameter("sortType");
				String scheme = request.getParameter("scheme");
				List sortList = gss.findProcessStep(" where specName='" + sort
						+ "' and scheme=" + scheme + " order by processPos ");
				List ret = sortList;
				JSONObject json = new JSONObject();
				JsonConfig cfg = new JsonConfig();
				cfg.registerJsonValueProcessor(java.util.Date.class,
						new DateJsonValueProcessor());
				cfg.registerJsonValueProcessor(java.sql.Date.class,
						new DateJsonValueProcessor());

				// BeanUtils.copyProperties();
				json.put("totalProperty", new Integer(ret.size()));

				JSONArray arr = JSONArray.fromObject(ret.toArray(), cfg);
				json.put("root", arr);

				response.getWriter().print(json);
			} catch (GSException e) {
				System.out.println("update error:" + e.getMessage());
				out.print("{success:false, data:'false'}");
			}
		}

		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
